package day13.lianxi;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther:小陈的Java
 */
public class AccountTest3 {
    public static void main(String[] args) {
        Account3 account3 = new Account3(0);
        Runnable runnable = new Customer3(account3);
        new Thread(runnable,"1").start();
        new Thread(runnable,"2").start();

    }
}
class Account3 {
    private int money = 0;
    private Lock lock = new ReentrantLock();

    public Account3(int money) {
        this.money = money;
    }
    public void saveMoney(int money) {
        lock.lock();
        if (money > 0) {
            this.money += money;
            try {
                Thread.sleep(100);
                System.out.println(Thread.currentThread().getName() + "：存钱成功。余额为：" + this.money);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
}
class Customer3 implements Runnable {
    private Account3 account3;
    public Customer3(Account3 account3) {
        this.account3 = account3;
    }
    @Override
    public void run() {
        for (int i = 1; i <=3; i++) {
            account3.saveMoney(1000);
        }
    }
}
